﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using VideoRentalShop.Model;

namespace VideoRentalShop.Controller.Data
{
    public class GenreDataSource : DataSourceBase<Genre>
    {
        private GenreDetailsDataSource _genreDetailsSource;


        public GenreDataSource(MovieDbContext db, GenreDetailsDataSource genreDetailsSource) : base(db)
        {
            _genreDetailsSource = genreDetailsSource;
        }


        public DbSet<Genre> GetAll()
        {
            return _db.Genres;
        }


        public override bool IsValid(Genre item)
        {
            return _db.Entry(item).GetValidationResult().IsValid;
        }

        public override bool Add(Genre item)
        {
            var entry = _db.Entry<Genre>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Added;
                return Save();
            }

            return valid;
        }

        public override bool Edit(Genre item)
        {
            var entry = _db.Entry<Genre>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Modified;
                return Save();
            }

            return valid;
        }

        public override bool Remove(Genre item)
        {
            var result = _db.Genres.Find(item.Id);
            if (result != null)
            {
                _genreDetailsSource.Remove(item);
                _db.Entry(result).State = EntityState.Deleted;
                return Save();
            }

            return false;
        }
    }
}
